<template>
  <div class="layout">
    <Sidebar />
    <div class="charity-org-container">
      <a-card class="box-card">
        <template #title>
          <div class="card-title-wrapper">
            <span>慈善组织管理</span>
            <a-button
                type="primary"
                @click="deployContract"
                :loading="isDeploying"
            >
              部署合约
            </a-button>
          </div>
        </template>

        <!-- 创建捐赠项目 -->
        <a-card class="section-card">
          <template #title>
            <span>创建捐赠项目</span>
          </template>
          <a-form :model="projectForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-form-item label="项目名称" required>
              <a-input v-model:value="projectForm.projectName" placeholder="请输入项目名称" />
            </a-form-item>
            <a-form-item label="项目描述" required>
              <a-textarea v-model:value="projectForm.description" placeholder="请输入项目描述" :rows="4" />
            </a-form-item>
            <a-form-item label="受益人地址" required>
              <a-input v-model:value="projectForm.beneficiaryAddress" placeholder="请输入受益人地址" />
            </a-form-item>
            <a-form-item label="目标金额" required>
              <a-input-number v-model:value="projectForm.targetAmount" :min="1" placeholder="请输入目标金额" style="width: 100%" />
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 6 }">
              <a-button type="primary" @click="createProject">创建项目</a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 注册管理 -->
        <a-card class="section-card">
          <template #title>
            <span>注册管理</span>
          </template>
          <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-form-item label="监管机构地址">
              <a-input v-model:value="regulatorAddress" placeholder="请输入监管机构地址" />
              <template #extra>
                <a-button type="primary" @click="registerRegulator" :disabled="!regulatorAddress">
                  注册监管机构
                </a-button>
              </template>
            </a-form-item>
            <a-form-item label="受益人地址">
              <a-input v-model:value="beneficiaryAddress" placeholder="请输入受益人地址" />
              <template #extra>
                <a-button type="primary" @click="registerBeneficiary" :disabled="!beneficiaryAddress">
                  注册受益人
                </a-button>
              </template>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 申请审批 -->
        <a-card class="section-card">
          <template #title>
            <span>申请审批</span>
          </template>
          <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-form-item label="申请ID">
              <a-input v-model:value="applicationId" placeholder="请输入申请ID" />
              <template #extra>
                <a-button type="primary" @click="approveApplication" :disabled="!applicationId">
                  批准申请
                </a-button>
              </template>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 申请列表 -->
        <a-card class="section-card">
          <template #title>
            <span>申请列表</span>
          </template>
          <a-table
              :columns="applicationColumns"
              :data-source="applications"
              :loading="isLoadingApplications"
              row-key="id"
          >
            <template #bodyCell="{ column, text }">
              <template v-if="column.dataIndex === 'status'">
                <a-tag :color="text === 'approved' ? 'green' : 'red'">{{ text }}</a-tag>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-card>
    </div>
  </div>
</template>
<script>
import { message } from 'ant-design-vue';
import axios from 'axios';
import Sidebar from '../components/Siderbar.vue';

export default {
  name: 'CharityOrg',
  components: {
    Sidebar
  },
  data() {
    return {
      isDeploying: false,
      projectForm: {
        projectName: '',
        description: '',
        beneficiaryAddress: '',
        targetAmount: null
      },
      regulatorAddress: '',
      beneficiaryAddress: '',
      applicationId: '',
      applications: [], // 申请列表
      isLoadingApplications: false, // 加载状态
      applicationColumns: [
        {
          title: '申请ID',
          dataIndex: 'applicationId',
          key: 'applicationId'
        },
        {
          title: '项目名称',
          dataIndex: 'description',
          key: 'description'
        },
        {
          title: '受益人地址',
          dataIndex: 'donor',
          key: 'donor'
        },
        {
          title: '申请金额',
          dataIndex: 'amount',
          key: 'amount'
        },
        {
          title: '状态',
          dataIndex: 'approved',
          key: 'approved',
          scopedSlots: { customRender: 'status' }
        }
      ]
    };
  },
  methods: {
    async deployContract() {
      try {
        this.isDeploying = true;
        const response = await axios.post('/api/charity-org/deploy');
        if (response.data) {
          message.success('合约部署成功，合约地址：' + response.data);
          console.log('合约部署成功，合约地址：' + response.data);
        }
      } catch (error) {
        message.error('合约部署失败：' + error.message);
      } finally {
        this.isDeploying = false;
      }
    },

    async createProject() {
      try {
        if (!this.validateProjectForm()) {
          return;
        }

        const params = new URLSearchParams();
        params.append('projectName', this.projectForm.projectName);
        params.append('description', this.projectForm.description);
        params.append('beneficiaryAddress', this.projectForm.beneficiaryAddress);
        params.append('targetAmount', this.projectForm.targetAmount);

        const response = await axios.post('/api/charity-org/project', params);
        if (response.data) {
          message.success('项目创建成功');
          this.resetProjectForm();
        }
      } catch (error) {
        message.error('项目创建失败：' + error.message);
      }
    },

    validateProjectForm() {
      if (!this.projectForm.projectName) {
        message.warning('请输入项目名称');
        return false;
      }
      if (!this.projectForm.description) {
        message.warning('请输入项目描述');
        return false;
      }
      if (!this.projectForm.beneficiaryAddress) {
        message.warning('请输入受益人地址');
        return false;
      }
      if (!this.projectForm.targetAmount) {
        message.warning('请输入目标金额');
        return false;
      }
      return true;
    },

    resetProjectForm() {
      this.projectForm = {
        projectName: '',
        description: '',
        beneficiaryAddress: '',
        targetAmount: null
      };
    },

    async registerRegulator() {
      try {
        const params = new URLSearchParams();
        params.append('regulatorAddress', this.regulatorAddress);

        await axios.post('/api/charity-org/registerRegulator', params);
        message.success('监管机构注册成功');
        this.regulatorAddress = '';
      } catch (error) {
        message.error('监管机构注册失败：' + error.message);
      }
    },

    async registerBeneficiary() {
      try {
        const params = new URLSearchParams();
        params.append('beneficiaryAddress', this.beneficiaryAddress);

        await axios.post('/api/charity-org/registerBeneficiary', params);
        message.success('受益人注册成功');
        this.beneficiaryAddress = '';
      } catch (error) {
        message.error('受益人注册失败：' + error.message);
      }
    },

    async approveApplication() {
      try {
        await axios.post(`/api/charity-org/application/${this.applicationId}/approve`);
        message.success('申请审批成功');
        this.applicationId = '';
        this.fetchApplications(); // 刷新申请列表
      } catch (error) {
        message.error('申请审批失败：' + error.message);
      }
    },

    async fetchApplications() {
      try {
        this.isLoadingApplications = true;
        const response = await axios.get('/api/charity-org/getAllApplications');
        if (response.data) {
          this.applications = response.data;
        }
      } catch (error) {
        message.error('获取申请列表失败：' + error.message);
      } finally {
        this.isLoadingApplications = false;
      }
    }
  },
  mounted() {
    // 页面加载时获取申请列表
    this.fetchApplications();
  }
};
</script>

<style scoped>
.layout {
  display: flex;
  min-height: 100vh;
}

.charity-org-container {
  padding: 20px;
  flex: 1;
  margin-left: 256px;
}

.card-title-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.section-card {
  margin-bottom: 20px;
}

.ant-form-item-extra {
  margin-top: 10px;
}

.box-card {
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.ant-form-item {
  margin-bottom: 24px;
}

.ant-button {
  height: 32px;
  padding: 0 16px;
}

.ant-input,
.ant-input-number {
  border-radius: 4px;
}

.ant-textarea {
  border-radius: 4px;
  resize: vertical;
}

.ant-card-head {
  border-bottom: 1px solid #f0f0f0;
}

.ant-card-head-title {
  padding: 16px 0;
  font-size: 16px;
  font-weight: 500;
}

/* 部署按钮特殊样式 */
.card-title-wrapper .ant-btn {
  margin-left: 16px;
  background-color: #52c41a;
  border-color: #52c41a;
}

.card-title-wrapper .ant-btn:hover {
  background-color: #73d13d;
  border-color: #73d13a;
}

.card-title-wrapper .ant-btn:active {
  background-color: #389e0d;
  border-color: #389e0d;
}

/* 申请列表表格样式 */
.ant-table {
  margin-top: 20px;
}

.ant-table-thead > tr > th {
  background-color: #f9f9f9;
  font-weight: 500;
}
</style>